package com.dtai.simulator;

import android.util.Log;
import android.widget.Toast;

import com.hivemq.client.mqtt.MqttClient;
import com.hivemq.client.mqtt.mqtt3.Mqtt3AsyncClient;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class MqttHelper {

    private Mqtt3AsyncClient mqttClient;
    private final Executor executor = Executors.newSingleThreadExecutor();

    public static final String TOPIC_SUB = "request/mqtt";
    public static final String TOPIC_PUB = "ai/result";

    private final static MqttHelper INSTANCE = new MqttHelper();
    private MqttHelper(){}
    public static MqttHelper getInstance(){
        return INSTANCE;
    }

    // 初始化客户端
    public void initClient(String clientId) {
        mqttClient = MqttClient.builder()
                .useMqttVersion3()
                .identifier(clientId)
                .serverHost(Config.IP) // HiveMQ 公共 Broker
                .serverPort(1883)
                .buildAsync();
    }

    // 连接到 Broker（带回调）
    public void connect(ConnectionCallback callback) {
        executor.execute(() -> {
            mqttClient.connect()
                    .whenComplete((connAck, throwable) -> {
                        if (throwable != null) {
                            Log.e("MQTT", "连接失败: " + throwable.getMessage());
//                            Toast.makeText(SimulatorApplication.in)
                            callback.onError(throwable);
                        } else {
                            Log.d("MQTT", "连接成功");
                            callback.onSuccess();
                        }
                    });
        });
    }

    // 订阅主题
    public void subscribe(String topic, MessageCallback messageCallback) {
        mqttClient.subscribeWith()
                .topicFilter(topic)
                .callback(publish -> {
                    String message = new String(publish.getPayloadAsBytes());
                    Log.d("MQTT", "收到消息: " + message);
                    messageCallback.onMessage(message);
                })
                .send()
                .whenComplete((subAck, throwable) -> {
                    if (throwable != null) {
                        Log.e("MQTT", "订阅失败: " + throwable.getMessage());
                    } else {
                        Log.d("MQTT", "已订阅主题: " + topic);
                    }
                });
    }

    // 发布消息
    public void publish(String topic, String message) {
        executor.execute(() -> {
            mqttClient.publishWith()
                    .topic(topic)
                    .payload(message.getBytes())
                    .send()
                    .whenComplete((publish, throwable) -> {
                        if (throwable != null) {
                            Log.e("MQTT", "发布失败: " + throwable.getMessage());
                        } else {
                            Log.d("MQTT", "消息已发布: " + topic + " -> " + message);
                        }
                    });
        });
    }

    // 断开连接
    public void disconnect() {
        if (mqttClient != null) {
            mqttClient.disconnect();
            mqttClient = null;
        }
    }

    // 回调接口
    public interface ConnectionCallback {
        void onSuccess();
        void onError(Throwable throwable);
    }

    public interface MessageCallback {
        void onMessage(String message);
    }
}
